package cn.zj.smart.util.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

public class BaseExcelUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * @param filePath 绝对路径
     * @param sheetIndex 第几个表，从0开始
     * @return Sheet对象
     */
    public static Sheet getSheet(String filePath, int sheetIndex) {
        InputStream inputStream = null;
        try {
            File file = new File(filePath);
            System.out.println(file.getAbsolutePath());
            inputStream = new FileInputStream(file);
            return getSheet(filePath, inputStream, sheetIndex);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("error to get inputStream");
        }
        return null;
    }

    private static Sheet getSheet(String filePath, InputStream inputStream, int sheetIndex) {
        try {
            // TODO 后缀名判断不一定准确，应该判断文件头的方式，空了改一下
            if (filePath.indexOf(".xlsx") != -1) {
                XSSFWorkbook wb = new XSSFWorkbook(inputStream);
                return wb.getSheetAt(sheetIndex);
            } else {
                HSSFWorkbook wb = new HSSFWorkbook(inputStream);
                return wb.getSheetAt(sheetIndex);
            }
        } catch (Exception e) {
            LOGGER.warn("获取表错误：{}", filePath + "==" + sheetIndex);
        }
        return null;
    }
}
